import Foundation
import UserNotifications

class NotificationManager {
    static let shared = NotificationManager()
    
    private init() {}
    
    // 请求通知权限
    func requestPermission(completion: @escaping (Bool) -> Void) {
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
            DispatchQueue.main.async {
                completion(granted)
            }
        }
    }
    
    // 安排定时提醒通知
    func scheduleReminders(interval: Int, startTime: Date, endTime: Date, sound: Bool, vibration: Bool) {
        // 先移除所有现有的提醒
        UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
        
        let calendar = Calendar.current
        
        // 获取今天的开始和结束时间点
        let startHour = calendar.component(.hour, from: startTime)
        let startMinute = calendar.component(.minute, from: startTime)
        let endHour = calendar.component(.hour, from: endTime)
        let endMinute = calendar.component(.minute, from: endTime)
        
        var currentTime = calendar.date(bySettingHour: startHour, minute: startMinute, second: 0, of: Date())!
        let today = calendar.startOfDay(for: Date())
        let endTimeToday = calendar.date(bySettingHour: endHour, minute: endMinute, second: 0, of: today)!
        
        var notificationCount = 0
        
        // 按照间隔创建一系列通知
        while currentTime < endTimeToday {
            let content = UNMutableNotificationContent()
            content.title = "该喝水了！"
            content.body = "保持水分很重要，现在喝一杯吧"
            content.badge = 1
            
            if sound {
                content.sound = UNNotificationSound.default
            }
            
            // 计算从现在到通知时间的秒数
            let triggerDate = calendar.dateComponents([.hour, .minute], from: currentTime)
            let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDate, repeats: true)
            
            let request = UNNotificationRequest(
                identifier: "waterReminder-\(notificationCount)",
                content: content,
                trigger: trigger
            )
            
            UNUserNotificationCenter.current().add(request)
            
            // 增加间隔时间
            currentTime = calendar.date(byAdding: .minute, value: interval, to: currentTime)!
            notificationCount += 1
        }
    }
} 